//
//  FirstDetailTravelViewController.m
//  BTRIP
//
//  Created by dllo on 15/11/14.
//  Copyright © 2015年 johnbk. All rights reserved.
//

#import "FirstDetailTravelViewController.h"
#import "FirstTitleDetailTravelTableViewCell.h"
#import "FirstPicTableViewCell.h"
#import "FirstDetailTravelModel.h"
#import "FirstSmallDetailModel.h"
#import "FirstSmallerDetailModel.h"
#import "TopView.h"
#import "FirstDetailTravelModel.h"
#import "FirstSmallDetailModel.h"
#import "FirstSmallerDetailModel.h"
#import "FirstLastDetailModel.h"
#import <SDWebImageManager.h>
#import <UIImageView+WebCache.h>
#import <AFHTTPSessionManager.h>
#import "SectionView.h"
#import "SuitableHeight.h"
#import <MBProgressHUD.h>
#import "EndView.h"
#import "CoreDataManager.h"
#import "CollectDiaryModel.h"
#import "UMSocial.h"
@interface FirstDetailTravelViewController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIView *navView;
@property (nonatomic, retain) UIButton *popButton;
@property (nonatomic, retain) UIButton *selectButton;
@property (nonatomic, retain) UIButton *shareButton;
//详情页总的大字典
@property (nonatomic, retain) NSDictionary *dic;
//trip_days 数组
@property (nonatomic, retain) NSMutableArray *trip_daysArray;
//nodes数组
@property (nonatomic, retain) NSMutableArray *nodesArray;

@property (nonatomic, retain) NSMutableArray *notesArray;

@property (nonatomic, retain) NSMutableArray *resultArray;
@property (nonatomic, retain) TopView *topView;
@property (nonatomic, retain) EndView *endView;
@property (nonatomic, retain) UIImageView *imgView;
@property (nonatomic, assign) CGFloat image_width;
@property (nonatomic, assign) CGFloat image_height;
@property (nonatomic, retain)MBProgressHUD *hud;
@property (nonatomic, retain) UIVisualEffectView *visual;
@property (nonatomic, retain) CoreDataManager *manger;
@property (nonatomic, retain) FirstDetailTravelModel *firstDetail;
@end

@implementation FirstDetailTravelViewController

- (void)dealloc{
    [_tableView release];
    [_navView release];
    [_trip_daysArray release];
//    [_resultArray release];
    [super dealloc];
}

//- (void)viewWillAppear:(BOOL)animated {
//    //获取数据请求
//    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"CollectDiaryModel"];
//    request.predicate = [NSPredicate predicateWithFormat:@"theUrl = %@",self.ID];
//    //相数据管理器请求数据
//    NSArray *requestArray = [_manger.managedObjectContext executeFetchRequest:request error:nil];
//    if (requestArray.count == 0) {
//        self.selectButton.selected = NO;
//    }else{
//        self.selectButton.selected = YES;
//    }
//    
//}
//

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.trip_daysArray = [NSMutableArray array];
    self.nodesArray = [NSMutableArray array];
    self.notesArray = [NSMutableArray array];
    self.resultArray = [NSMutableArray array];
    self.dic = [NSDictionary dictionary];

    //coredata收藏
    self.manger = [CoreDataManager shareManager];
    NSLog(@"url: %@", [_manger applicationDocumentsDirectory]);
    
    //隐藏导航条
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self creatDetailTableView];
    [self loadData];
    [self createNaviView];
    
    self.hud = [[MBProgressHUD alloc]init];
    [self.view addSubview:self.hud];
    [_hud release];
    [self.hud show:YES];

    //头视图
    self.topView = [[TopView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH , KHEIGHT/ 3)];
    self.topView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = self.topView;
    
    //悬浮按钮
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//    button.frame = CGRectMake(10 * SWIDTH, KHEIGHT - 40, 30 * SWIDTH, 30 * SWIDTH);
//    button.layer.cornerRadius = button.frame.size.width / 2;
//    button.layer.masksToBounds = YES;
//    button.backgroundColor = [UIColor whiteColor];
//    
//    [button setBackgroundImage:[UIImage imageNamed:@"xuanfu"] forState:UIControlStateNormal];
//    [self.view addSubview:button];
    
}
#pragma mark 游记详情解析数据
- (void)loadData{
//    NSLog(@"%@",self.ID);
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session GET:[NSString stringWithFormat:@"http://chanyouji.com/api/trips/%@.json",self.ID] parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        self.dic = (NSDictionary *)responseObject;
       // 头视图Model
        FirstDetailTravelModel *firstDetail = [[FirstDetailTravelModel alloc]init];
        [firstDetail setValuesForKeysWithDictionary:self.dic];
        self.topView.firstDetail = firstDetail;
        if (firstDetail.tip != nil) {
            //尾视图
            self.endView = [[EndView alloc] initWithFrame:CGRectMake(0, 0, KWIDTH, 500 * SWIDTH)];
            self.endView.backgroundColor = [UIColor colorWithRed:0.937 green:0.937 blue:0.957 alpha:1];
            self.tableView.tableFooterView = self.endView;
            self.endView.firstDetail = firstDetail;
        }else{
            self.endView.firstDetail = nil;
            self.endView = nil;
        }
        
        NSArray *tripArray = [self.dic objectForKey:@"trip_days"];
        
        for (NSDictionary *dic in tripArray) {
            FirstSmallDetailModel *firstSmall = [[FirstSmallDetailModel alloc]init];
            [firstSmall setValuesForKeysWithDictionary:dic];
            [self.imgView sd_setImageWithURL:[NSURL URLWithString:firstDetail.front_cover_photo_url] placeholderImage:[UIImage imageNamed:@"background"]];
            [self.trip_daysArray addObject:firstSmall];
            [firstSmall release];
        }
        [self.hud hide:YES];
        
        
        
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"请求失败:error: %@",error);
    }];
}

#pragma mark 创建tableView
- (void)creatDetailTableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, -20, KWIDTH, KHEIGHT + 20) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor colorWithRed:1.000 green:1.000 blue:1.000 alpha:1];
    self.tableView.separatorColor = [UIColor lightGrayColor];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.bounces = NO;
    [self.view addSubview:self.tableView];
    [_tableView release];
    //注册重用标识
    [self.tableView registerClass:[FirstTitleDetailTravelTableViewCell class] forCellReuseIdentifier:@"firstTitle"];
    [self.tableView registerClass:[FirstPicTableViewCell class] forCellReuseIdentifier:@"firstPic"];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section <= self.trip_daysArray.count) {
        FirstSmallDetailModel *firstSmall = [self.trip_daysArray objectAtIndex:indexPath.section];
        NSArray *array1 = firstSmall.nodes;
        FirstSmallerDetailModel *firstSmaller = [[FirstSmallerDetailModel alloc]init];
           for (int i = 0; i < array1.count; i++) {
            firstSmaller = array1[i];
//               NSLog(@"🍊🍊%@",firstSmaller);
//               NSLog(@"==== %ld",array1.count);
        }
        [self.nodesArray addObject:firstSmaller];
        [firstSmaller release];
        
        FirstLastDetailModel *firstlast = [firstSmaller.notes objectAtIndex:indexPath.row];
        if (firstlast.photo != nil) {
            
            FirstPicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"firstPic"];
            cell.firstLast = firstlast;
            cell.backgroundColor = [UIColor colorWithRed:0.949 green:0.949 blue:0.949 alpha:1];
           
            return cell;
        }else{
            FirstTitleDetailTravelTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"firstTitle"];
            cell.firstLast = firstlast;
            cell.backgroundColor = [UIColor colorWithRed:0.949 green:0.949 blue:0.949 alpha:1];
            return cell;
        }
    }else{
        return nil;
    }
}
#pragma mark 返回的cell数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //返回的cell数
    if (section <= self.trip_daysArray.count) {
        FirstSmallDetailModel *firstSmall = self.trip_daysArray[section];
        NSArray *array1 = firstSmall.nodes;
        NSArray *array2 = [NSArray array];
        for (FirstSmallerDetailModel *firstSmaller1 in array1) {
            array2 = firstSmaller1.notes;
        }
        return array2.count;
    }else{
        return 0;
    }
}
#pragma mark cell 高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    FirstSmallDetailModel *firstSmall = [self.trip_daysArray objectAtIndex:indexPath.section];
    NSArray *array1 = firstSmall.nodes;
    
    FirstSmallerDetailModel *firstSmaller = [[FirstSmallerDetailModel alloc]init];
    for (int i = 0; i < array1.count; i++) {
        firstSmaller = array1[i];
//        NSLog(@"=== %@",firstSmaller);
    }
    FirstLastDetailModel *firstLast = [firstSmaller.notes objectAtIndex:indexPath.row];
    
    if (firstLast.photo != nil) {
        NSString *str1 = [NSString stringWithFormat:@"%@",[firstLast.photo objectForKey:@"image_width"]];
        self.image_width = [str1 floatValue];
        
        NSString *str2 = [NSString stringWithFormat:@"%@",[firstLast.photo objectForKey:@"image_height"]];
        self.image_height = [str2 floatValue];
        CGFloat picHeight = (KWIDTH - 10) * self.image_height / self.image_width;
        CGFloat height = [SuitableHeight suitableHeight:firstLast.textDescription andWidth:KWIDTH - 10 andFont:14];
        return picHeight + height + 25 ;
    }else{
        CGFloat height = [SuitableHeight suitableHeight:firstLast.textDescription andWidth:KWIDTH - 10 andFont:14];
        return height + 50;
    }
}

#pragma mark 自定义tableView的区头 
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    SectionView *sectionView = [[SectionView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, 40 * SWIDTH)];
    FirstSmallDetailModel *firstModel = self.trip_daysArray[section];
    
    if (firstModel.trip_date != nil) {
        NSString *str = [NSString stringWithFormat:@"DAY%@  %@", firstModel.day, firstModel.trip_date];
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:str];
        NSRange rangeOne = [str rangeOfString:[NSString stringWithFormat:@"%@",firstModel.trip_date]];
        [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:rangeOne];
        sectionView.sectionLabel.attributedText = attrStr;
        return sectionView;
    }else{
        NSString *str = [NSString stringWithFormat:@"DAY%@",firstModel.day];
        sectionView.sectionLabel.text = str;
        return  sectionView;
    }
}

//返回的section数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.trip_daysArray.count;
}


//分区头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}


//cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark 创建navView
- (void)createNaviView{
    self.navView = [[UIView alloc]initWithFrame:CGRectMake(0, -20, KWIDTH, 84)];
    [self.view addSubview:self.navView];
    [_navView release];
    self.navView.alpha = 0;
   
    self.imgView = [[UIImageView alloc]initWithFrame:self.navView.bounds];
    [self.navView addSubview:self.imgView];
    [self.imgView release];
    self.visual = [[UIVisualEffectView alloc]initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    self.visual.frame = self.navView.bounds;
    
    [self.imgView addSubview:self.visual];
    [_visual release];
    self.popButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.popButton setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui-4"] forState:UIControlStateNormal];
    self.popButton.frame = CGRectMake(20 * SWIDTH, 35 * SWIDTH, 20 * SWIDTH , 20 * SWIDTH);
    [self.popButton addTarget:self action:@selector(popButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.popButton];
    
    //收藏按钮
//    self.selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [self.selectButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xin"] forState:UIControlStateNormal];
//    self.selectButton.frame = CGRectMake(self.popButton.frame.origin.x + self.popButton.frame.size.width + 230 * SWIDTH, self.popButton.frame.origin.y, 20 * SWIDTH, 20 * SWIDTH);
//    [self.selectButton addTarget:self action:@selector(selectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:self.selectButton];
    
    //分享按钮
   self.shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.shareButton setBackgroundImage:[UIImage imageNamed:@"iconfont-share-4"] forState:UIControlStateNormal];
    self.shareButton.frame = CGRectMake(self.popButton.frame.size.width + self.popButton.frame.origin.x + 280, self.popButton.frame.origin.y, 20 * SWIDTH, 20 * SWIDTH);
    [self.shareButton addTarget:self action:@selector(shareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.shareButton];
}
#pragma mark navView随着偏移量偏移事件
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.y < 20) {
        [self.popButton setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui-4"] forState:UIControlStateNormal];
        [self.selectButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xin"] forState:UIControlStateNormal];
        [self.shareButton setBackgroundImage:[UIImage imageNamed:@"iconfont-share-3"] forState:UIControlStateNormal];
        self.navView.alpha = 0;
    }else if (scrollView.contentOffset.y > 20 && scrollView.contentOffset.y < self.topView.frontImage.frame.size.height){
        self.navView.alpha = scrollView.contentOffset.y / self.topView.frontImage.frame.size.height;
        self.visual.alpha = scrollView.contentOffset.y / self.topView.frontImage.frame.size.height - 0.2;
        [self.popButton setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui-3"] forState:UIControlStateNormal];
        [self.shareButton setBackgroundImage:[UIImage imageNamed:@"iconfont-share-2"] forState:UIControlStateNormal];
        [self.selectButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xin-2"] forState:UIControlStateNormal];
    }else{
//        self.navView.backgroundColor = [UIColor whiteColor];
        self.navView.alpha = 1;
        [self.popButton setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui-3"] forState:UIControlStateNormal];
        [self.shareButton setBackgroundImage:[UIImage imageNamed:@"iconfont-share-2"] forState:UIControlStateNormal];
        [self.selectButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xin-2"] forState:UIControlStateNormal];
    }
}

//popButton点击事件
- (void)popButtonAction:(UIButton *)button{
    [self.navigationController popViewControllerAnimated:YES];
}
//selectButton点击事件
- (void)selectButtonAction:(UIButton *)button{
//    button.selected = !button.isSelected;
//    if (button.selected == YES) {
//        CollectDiaryModel *diary = [NSEntityDescription insertNewObjectForEntityForName:@"CollectDiaryModel" inManagedObjectContext:_manger.managedObjectContext];
//        diary.name = _firstDetail.name;
//        diary.imgUrl = _firstDetail.front_cover_photo_url;
//        diary.theUrl = self.ID;
//        [_manger saveContext];
//        NSLog(@"收藏成功");
//    }else{
//        //系统自带的查找功能
//        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
//        NSEntityDescription *entity = [NSEntityDescription entityForName:@"CollectDiaryModel" inManagedObjectContext:_manger.managedObjectContext];
//        [fetchRequest setEntity:entity];
//        
//        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"theUrl CONTAINS %@",self.ID];
//        [fetchRequest setPredicate:predicate];
//        
//        NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"theUrl" ascending:YES];
//        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sort, nil]];
//        
//        NSError *error = nil;
//        NSArray *fetchObjects = [_manger.managedObjectContext executeFetchRequest:fetchRequest error:&error];
//        [self.resultArray removeAllObjects];
//        self.resultArray = [NSMutableArray arrayWithArray:fetchObjects];
//        
//        if (fetchObjects == nil) {
//            NSLog(@"没有收藏记录: %@",error);
//        }else{
//            for (CollectDiaryModel *diary in _resultArray) {
//                [_manger.managedObjectContext deleteObject:diary];
//            }
//            [_manger saveContext];
//            NSLog(@"收藏成功");
//        }
//    }
    
}
//shareButton点击事件
- (void)shareButtonAction:(UIButton *)button{
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"56567db5e0f55a58fc00040d" shareText:[NSString stringWithFormat:@"http://chanyouji.com/api/trips/%@.json",self.ID] shareImage:nil shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,nil] delegate:NULL];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
